package com.minarto.display.loader {
	import com.minarto.utils.GPool;
	import de.polygonal.core.ObjectPool;
	import flash.display.*;
	import flash.net.URLRequest;
	
	import flash.events.*;

	/**
	 * @author minarto@minarto.com
	 */
	[Event(name = "complete", type = "flash.events.Event")]
	[Event(name = "ioError", type = "flash.events.IOErrorEvent")]
	public class DisplayLoader extends EventDispatcher {
		private var	_loader:Loader,
					_content:DisplayObject;
					
					
		public var	onComplete:Function,
					onIoError:Function;
		
		
		public function getContent():DisplayObject {
			return	_content;
		}
		
		
		public function load($src:String):void {
			var info:LoaderInfo, p:ObjectPool, r:URLRequest;
			
			close();
			
			_content = null;
			if (!$src) return;
			
			p = GPool.getPool(Loader);
			_loader = p.object;
			info = _loader.contentLoaderInfo;
			info.addEventListener(Event.COMPLETE, _onComplete, false, 0, true);
			info.addEventListener(IOErrorEvent.IO_ERROR, _onIoError, false, 0, true);
			
			p = GPool.getPool(URLRequest);
			r = p.object;
			r.url = $src;
				
			_loader.load(r);
			p.object = r;
		}
		
		
		public function close():void {
			var info:LoaderInfo;
			
			if(_loader){
				_loader.close();
				
				info = _loader.contentLoaderInfo;
				info.removeEventListener(Event.COMPLETE, _onComplete);
				info.removeEventListener(IOErrorEvent.IO_ERROR, _onIoError);
			
				GPool.getPool(Loader).object = _loader;
				_loader = null;
			}
		}
		
		
		private function _onComplete($e:Event):void {
			var info:LoaderInfo;
			
			info = _loader.contentLoaderInfo;
			_content = info.content;
			
			dispatchEvent($e);
			
			if(Boolean(onComplete)){
				onComplete(this);
			}
			
			info.removeEventListener(Event.COMPLETE, _onComplete);
			info.removeEventListener(IOErrorEvent.IO_ERROR, _onIoError);
			
			GPool.getPool(Loader).object = _loader;
			_loader = null;
		}
		
		
		private function _onIoError($e:IOErrorEvent):void {
			var info:LoaderInfo;
			
			dispatchEvent($e);
			
			if(Boolean(onIoError)){
				onIoError(this);
			}
			
			info = _loader.contentLoaderInfo;
			info.removeEventListener(Event.COMPLETE, _onComplete);
			info.removeEventListener(IOErrorEvent.IO_ERROR, _onIoError);
			
			GPool.getPool(Loader).object = _loader;
			_loader = null;
		}
	}
}